import { createApp } from 'vue'
import App from './App.vue'
import '@/assets/less/index.less'
import router from './router'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import { createPinia } from 'pinia'
import '@/api/mock.js'
import api from './api/api'
import { useAllDataStore } from '@/stores'

function isRouter(to) {
  return router.getRoutes().filter((item) => item.path === to.path).length > 0
}

// 路由守卫 ， 不存在页面则 统一处理
router.beforeEach((to, from) => {
  if (to.path !== '/login' && !store.state.token) {
    return { name: 'login' }
  }
  if (!isRouter(to)) {
    return { name: '404' }
  }
})

const pinia = createPinia()
const app = createApp(App)
// 全局挂载api 对象 。 全局使用
app.config.globalProperties.$api = api // axios 请请求 注册到全局
app.use(ElementPlus).use(pinia)

const store = useAllDataStore()
store.addMenu(router, 'refresh')

app.use(router).mount('#app')

// ElementPlusIcons 图标注入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}
